package com.myebills.ebpsfrontend.cust.maxis;

import com.myebills.ebpsfrontend.cust.controller.*;
import com.myebills.ebpsfrontend.cust.utils.*;
import com.checkfree.isolutions.customer.persist.*;
import com.checkfree.isolutions.admin.ObjectId;
import com.checkfree.isolutions.statement.StatementSection;
import com.checkfree.isolutions.statement.persist.*;
import com.checkfree.isolutions.utility.CFiError;
import java.util.*;
import java.text.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.ibm.logging.ILogger;
import com.ibm.logging.IRecordType;

/**
 * Module Name  : CusBillListServlet_v1r00
 * Description  : Bill Listing for customer
 * Last Updated : 2002-10-10
 *
 * @author lhlue
 *
 * Remarks :
 *
 */

public class CusBillListServlet_v1r00 extends EbppxTransactionServlet {
    //retrieve previous 6 months statements
    ILogger trcLogger = null;

    public void doTransaction(
    HttpServletRequest req,
    HttpServletResponse res)
    throws ServletException {

        final String fName = "doTransaction";
        trcLogger = getTraceLogger(req);

        if (trcLogger.isLogging())
            trcLogger.entry(IRecordType.TYPE_INFO, this, fName);

        try {
            final HttpSession session = req.getSession(false);

            if (null == session)
                throw new IllegalStateException("no session established");

		    final String randomKey = (String) session.getAttribute(EbppxConstants.RANDOM_KEY);

            //Get attribute from session for the logon user
            final EbppxEcsUser ecsUser = (EbppxEcsUser) session.getAttribute(EbppxConstants.ECS_USER);
						
            EbppxUrlManager urlManager = getUrlManager(req);
            // get the account no selected in JSP
            String strAccNo = urlManager.getRequestParameter("accNo");
            //strAccNo = EncryptionHelper.decrypt(strAccNo,randomKey);

			String simNo = "";
			simNo = urlManager.getRequestParameter("simno");
			if(!simNo.equals(""))
				ecsUser.setSimNo(simNo);
			
            String strRedirect = urlManager.getRequestParameter("redirect");
			
			//get statement index
			String stmtIndex = "";
			int sIndex = 0;
			stmtIndex = urlManager.getRequestParameter("stmtIndex");
			if(stmtIndex != ""){
				sIndex = Integer.parseInt(EncryptionHelper.decrypt(stmtIndex,randomKey));
			}
			
            //get the vector of Accounts
            final Vector cfiAccounts = ecsUser.getAccounts();
            final Vector cfiAcctExtKeys = ecsUser.getAccountExternalKeys();
            Vector cfiStatements = new Vector();

//poon test start
            final Vector cfiOldAccounts = ecsUser.getOldAccounts();
            req.setAttribute("oldAccounts",cfiOldAccounts);

			//to get old acc no for selected new acc no
			String oldAccountNo = ecsUser.getOldAccount(cfiAcctExtKeys, cfiOldAccounts, strAccNo);
//poon test end

			//to check is there any old account number - start
			int oldAccountDisplayCount = 0;
			String oldAccountDisplay = "N";
			String accountId = "";
			String statementId = "";
			//for (java.util.Enumeration enumAccounts = cfiAcctExtKeys.elements(); enumAccounts.hasMoreElements();) {
			String accno = ecsUser.getSAccount();
			if(accno != null){
				//final String tAccountNo = (String) enumAccounts.nextElement();

                Merchant cfiMerchant = MerchantHomeImpl.singleton().findByName(ecsUser.getMerchantName());
                Account account = AccountHomeImpl.singleton().findByExternalKeyAndMerchant(accno, cfiMerchant);
				Statement cfiStatement =  null;
				if(account != null){
					accountId = account.getId().toString(true);
					cfiStatement =  StatementUtil.getStatement(account,EbppxCusConstants.STMT_START_MONTH,sIndex);
				}
                if(cfiStatement != null){
                	statementId = cfiStatement.getId().toString(true);
	        		StatementSection cfiRootSection = cfiStatement.getRootSection();
	        		if(cfiRootSection != null){
	        			String marketSegment = EbppxUtil.htmlEncode(cfiRootSection.getFieldText("MarketSegment"));
						if( marketSegment.equals("01") || marketSegment.equals("04")){
							ecsUser.setMSegment("GSM");
						}else if(marketSegment.equals("02") || marketSegment.equals("03") || marketSegment.equals("05")){
							ecsUser.setMSegment("OTH");
						}else{
							throw new ServletException("Market segment unknown.");
						}
						/**************************************************
						*
						*   Check is this account is stand-alone supp line
						*
						***************************************************/
						StatementSection cfiAccountSummarySection = cfiRootSection.getSection("AccountSummarySection");
						if(cfiAccountSummarySection == null){
							System.out.println("stand-alone supp line");
							ecsUser.setAccessType("P");
						}
	        		}
	        		
	        		Vector cfistatements = StatementUtil.getStatements(account, EbppxCusConstants.STMT_START_MONTH);
	        		if(cfistatements != null){
	        			String statementsCount = Integer.toString(cfistatements.size());
	        			session.setAttribute("statementsCount", statementsCount);
	        		}
					
					//cfiStatements.addElement(cfiStatement);
					req.setAttribute(EbppxConstants.CFI_STATEMENTS, cfiStatement);
					
					String urlStmtIndex = "";
					if(stmtIndex != ""){
						urlStmtIndex = EncryptionHelper.encodeURL(EncryptionHelper.encrypt(stmtIndex,randomKey));
					}else{
						urlStmtIndex = EncryptionHelper.encodeURL(EncryptionHelper.encrypt(Integer.toString(0),randomKey));
					}
					String param = "?stmtIndex=" + urlStmtIndex + "&statementId=" + EncryptionHelper.encodeURL(EncryptionHelper.encrypt(statementId,randomKey)) + "&accountId=" + EncryptionHelper.encodeURL(EncryptionHelper.encrypt(accountId,randomKey))+"&accNo="+accno;
					//System.out.println("stmtIndex ="+ urlStmtIndex);
					//System.out.println("url = "+ param);
					session.setAttribute("statementId", param);					
					
					req.setAttribute("oldAccountDisplay",oldAccountDisplay);
					//to check is there any old account number - end

					req.setAttribute(EbppxConstants.CFI_ACCOUNTS, cfiAccounts);
					req.setAttribute("acctExtKeys",cfiAcctExtKeys);

					//if an account has been selected then get the statements
					if (strAccNo !=null && !strAccNo.equals("")) {
						if (trcLogger.isLogging())
							trcLogger.text(IRecordType.TYPE_INFO, this, fName,"requested acc no: "+strAccNo);

						req.setAttribute("accNo", strAccNo);
						req.setAttribute("redirect", strRedirect);
					}

					session.setAttribute("fromPage","0");
					session.setAttribute(EbppxConstants.ECS_USER, ecsUser);
					req.setAttribute("forwardFrom",req.getRequestURI());
					forwardToMappedUrl(req, res, EbppxConstants.URL_JSP_PARAM+"_"+ecsUser.getMSegment());
					
                }else{
					session.setAttribute("errorMessage","There are no bills for this account.");
					redirectToMappedUrl(
					req,
					res,
					"urlLogonFailure",
					"");
				}

			}

        }
        catch (Throwable t) {
			System.out.println(t.toString());
            throw new ServletException(t.toString(), t);
        }
        finally {
            if (trcLogger.isLogging())
                trcLogger.exit(IRecordType.TYPE_INFO, this, fName);
        }

    }

}
